package ng.demo;

import java.net.URI;
import java.util.Scanner;

import javax.websocket.MessageHandler;

import org.apache.commons.lang3.StringUtils;

import ng.demo.ws.WebsocketClientEndpoint;

public class Main {

	public static void main(String... args) {
		Scanner sc = new Scanner(System.in);
		 WebsocketClientEndpoint client = null;
		for (;;) {
			System.out.println();
			System.out.println("Please enter command like exit, open, send [msg].");
			String com = sc.nextLine();
			if (StringUtils.isBlank(com)) {
				continue;
			}
			com = com.trim();
			if ("exit".equalsIgnoreCase(com)) {
				break;
			} else if ("open".equalsIgnoreCase(com)) {
				try {
					URI path = new URI("ws://localhost:8090/ws/demo");
					 client = createClient(path);
					 client.getLatch().await();
					System.out.println("Client open successfully.");
				} catch (Exception e) {
					e.printStackTrace();
					break;
				}
			} else if ("send ".startsWith(com.toLowerCase())) {
				if (client == null) {
					System.err.println("Please open client first.");
				}
				String message = com.substring(5);
				client.sendMessage(message);
				System.out.println("Send message : " + message);
			} else {
				System.err.println("Command not accept : " + com);
			}
		}
		sc.close();
	}

	static WebsocketClientEndpoint createClient(URI path) {
		final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(path);
		return clientEndPoint.setMessageHandler(new MessageHandler.Whole<String>() {
			@Override
			public void onMessage(String message) {
				System.out.println(message);
				clientEndPoint.sendMessage(StringUtils.reverse(message));
			}
		});
	}

}
